//
//  NetUtil.swift
//  weibo
//
//  Created by hm on 2020/5/3.
//  Copyright © 2020 hm. All rights reserved.
//

import AFNetworking

class NetUtil: AFHTTPSessionManager {
    //let是线程安全的
    //保证多线程访问时，也只会创建一个单例
    static let instance: NetUtil = {
        let netUtil = NetUtil()
        netUtil.responseSerializer.acceptableContentTypes?.insert("text/html")
        netUtil.responseSerializer.acceptableContentTypes?.insert("text/plain")
        netUtil.responseSerializer.acceptableContentTypes?.insert("application/json")
        return netUtil
    }()
}

// MARK:- 封装请求方法
extension NetUtil {
    func get(url: String, parameters: [String: Any], finish: @escaping(_ result: Any)->(), fail: @escaping(_ error: Error)->()) {
        get(url,
            parameters: parameters,
            headers: nil,
            progress: nil,
            success: {(task: URLSessionDataTask, result: Any)->Void in
                finish(result)
        })
        { (task: URLSessionDataTask?, error: Error)->Void in
            fail(error)
        }
    }
    
    func post(url: String, parameters: [String: Any], finish:@escaping(_ result: Any)->(),fail: @escaping(_ error: Error)->()) {
        post(url,
             parameters: parameters,
             headers: nil,
             progress: nil,
             success: { (task: URLSessionDataTask, result: Any) in
                    finish(result)
                },
             failure: { (task: URLSessionDataTask?, error: Error) in
                    fail(error)
                }
        )
    }
}

// MARK:- 加载accessToken
extension NetUtil {
    func loadAccessToken(codeString : String, finish : @escaping(_ result: Any)->(), fail: @escaping(_ errror: Error)->()) {
        // 1.获取请求的URl
        let url = "https://api.weibo.com/oauth2/access_token"
        
        // 2.获取请求的参数
        let parameters = ["client_id" : app_key,
                          "client_secret" : app_secret,
                          "grant_type" : "authorization_code",
                          "code" : codeString,
                          "redirect_uri" : redirect_url]
        
        // 3.发送网络请求
        post(url: url, parameters: parameters, finish: finish, fail: fail)
    }
}

// MARK:- 获取用户信息
extension NetUtil {
    func getUserInfo(accessToken : String, uid: String, finish : @escaping(_ result: Any)->(), fail: @escaping(_ errror: Error)->()) {
        // 1.获取请求的URLString
        let url = "https://api.weibo.com/2/users/show.json"
        
        // 2.获取请求的参数
        let parameters = ["access_token" : accessToken, "uid" : uid]
        
        // 3.发送网络请求
        get(url: url, parameters: parameters, finish: finish, fail: fail)
    }
}
